<template>
  <div>
    <atom-calendar-entry v-if="type === 'limitupDetail'" :value="defaultDate" @click="showCalendar = true" />
    <atom-calendar-entry v-else type="text" :value="defaultDate" @click="showCalendar = true" @click-left="clickLeft"
      @click-right="clickRight" />
    <atom-calendar ref="calendar" v-model="showCalendar" :defaultDate="defaultDate" :formatter="formatter"
      :show-confirm="false" :minDate="minDate" @confirm="confirm" />
  </div>
</template>

<script>
import { DatePlus, errorReport, formatDate } from '@/scripts/tools.js';
import { reqTradeDays } from '@/apis/index';
export default {
  props: {
    type: {
      type: 'limitupDetail' | 'ztfp',
      default: 'limitupDetail',
    },
    defaultDate: {
      type: Date,
      default: null,
    },
  },
  data() {
    return {
      showCalendar: false,
      minDate: new Date(),
      tradeDays: [],
    };
  },
  methods: {
    changeDate(type) {
      const symbolTips = type === 'left' ? -1 : 1;
      const nowIndex = this.tradeDays.findIndex(item => item === new DatePlus(this.defaultDate).format('yyyyMMdd'));
      // 最小一天或者最大一天，都不可再点击
      if ((nowIndex === 0 && symbolTips === -1) || (nowIndex === this.tradeDays.length - 1 && symbolTips === 1)) {
        return;
      }
      const dateStr = this.tradeDays[nowIndex + symbolTips];
      const date = new Date(formatDate(dateStr));
      this.$refs.calendar.reset(date);
      this.confirm(date);
    },
    clickLeft() {
      this.changeDate('left');
    },

    clickRight() {
      this.changeDate('right');
    },
    formatter(day) {
      const date = new DatePlus(day.date).format('yyyyMMdd');
      if (!this.tradeDays.includes(date)) {
        day.type = 'disabled';
      }
      return day;
    },
    getTradeDays() {
      reqTradeDays({ domain: 'CN', prev: 30 })
        .then(res => {
          const { isTradingday, tradeDate, prevDates } = res.data;
          this.tradeDays = prevDates;
          if (isTradingday) {
            this.tradeDays.push(tradeDate);
          }
          const firstDate = prevDates[0];
          this.minDate = new Date(formatDate(firstDate));
          // 未传参默认使用当前交易日
          if (!this.defaultDate) {
            const lastDay = this.tradeDays[this.tradeDays.length - 1];
            this.confirm(new Date(formatDate(lastDay)));
          }
        })
        .catch(err => {
          errorReport({
            name: `接口获取交易日错误,${err.name}`,
            message: err.message,
            stack: err.stack,
          });
        });
    },
    confirm(date) {
      this.showCalendar = false;
      this.$emit('updateDate', { date: new DatePlus(date).format('yyyyMMdd'), defaultDate: date });
    },
  },
  mounted() {
    this.getTradeDays();
  },
};
</script>
